package com.stone.framework.batch.listener;

import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.InitializingBean;

public abstract class AbstractJobExecutionListener implements JobExecutionListener, InitializingBean {

    private Flag flag;

    @Override
    public final void beforeJob(JobExecution jobExecution) {
        if (isDoBeforeJob()) {
            doBeforeJob(jobExecution);
        }
    }

    @Override
    public final void afterJob(JobExecution jobExecution) {
        if (isDoAfterJob()) {
            doAfterJob(jobExecution);
        }
    }

    protected boolean isDoBeforeJob() {
        return flag.isBefore();
    }

    protected boolean isDoAfterJob() {
        return flag.isAfter();
    }

    @Override
    public void afterPropertiesSet() {
        this.flag = this.flag == null ? Flag.AFTER : this.flag;
    }

    public void setFlag(Flag flag) {
        this.flag = flag;
    }

    protected abstract void doBeforeJob(JobExecution jobExecution);

    protected abstract void doAfterJob(JobExecution jobExecution);

    public static enum Flag {
        NONE(false, false), BEFORE(true, false), AFTER(false, true), ALL(true, true);

        private boolean beforeFlag;

        private boolean afterFlag;

        private Flag(boolean beforeFlag, boolean afterFlag) {
            this.beforeFlag = beforeFlag;
            this.afterFlag = afterFlag;
        }

        public boolean isBefore() {
            return beforeFlag;
        }

        public boolean isAfter() {
            return afterFlag;
        }
    }

}
